package md.frolov.bible.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import md.frolov.bible.Constants;

public class Book extends AbstractComparable implements IStructure, IViewLabelProvider, IURLProvider{
	private String id;
	private String name;
	private Module module;
	private List<Chapter> chapters = new ArrayList<Chapter>();
	
	private Book(){
		
	}
	
	public Book(String id){
		this.id = id;
	}
	
	public void setModule(Module parent){
		this.module = parent;
	}
	
	public Module getModule(){
		return module;
	}
	
	public void addChapter(Chapter c){
		chapters.add(c);
		c.setParent(this);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public Object[] getChildren() {
		return chapters.toArray();
	}
	
	public List<Chapter> getChapters(){
		return chapters;
	}

	@Override
	public Object getParent() {
		return module;	
	}

	@Override
	public boolean hasChildren() {
		return chapters.size()>0?true:false;
	}

	@Override
	public String getText() {
		return getName();
	}

	public String getId() {
		return id;
	}

	public String getLocalId() {
		return id;
//		String[] list = id.split("\\.");
//		return list[list.length-1];
	}

	public String getUrl() {
		return module.getUrl()+getId();
	}

	public Chapter getChapterByLocalId(String chapterId) {
		for (Iterator it = chapters.iterator(); it.hasNext();) {
			Chapter chapter = (Chapter) it.next();
			if(chapterId.equals(chapter.getLocalId()))
				return chapter;
		}
		return null;
	}
	
	public Chapter getFirstChapter(){
		return chapters.get(0);
	}
	
	public Chapter getLastChapter(){
		return chapters.get(chapters.size()-1);
	}

	public Chapter getChapterById(String id) {
		for (Iterator<Chapter> it = chapters.iterator(); it.hasNext();) {
			Chapter chapter = it.next();
			if(chapter.getId().equals(id)) return chapter;
		}
		return null;
	}
}
